﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
using System.Web.Mvc;
using DrugStore.Helper;
using DrugStore.Models;
using DrugStore.Exceptions;
using System.IO;

namespace DrugStore.Models
{
    public class ManageDiseaseModels
    {
        public String DiseaseId { get; set; }
        [Required(ErrorMessage = "Tên bệnh là bắt buộc")]
        [DisplayName("Tên bệnh: ")]
        public String DiseaseName { get; set; }

        [Required(ErrorMessage = "Mô tả ngắn là bắt buộc")]
        [DisplayName("Mô tả ngắn: ")]
        public String BriefDesc { get; set; }
        
        [DisplayName("Đường dẫn ảnh: ")]
        public String ImgPatch { get; set; }

        [Required(ErrorMessage = "Triệu chứng là bắt buộc")]
        [DisplayName("Nội dung: ")]
        public String Content { get; set; }

        [Required(ErrorMessage="Danh mục bệnh là bắt buộc")]
        [DisplayName("Danh mục")]
        public String DiseaseCategoryId { get; set; }               

        public List<SelectListItem> Categories { get; set; }

        public void setCategories(List<DiseaseCategory> categories)
        {
            List<SelectListItem> items = new List<SelectListItem>();
            foreach (DiseaseCategory dc in categories) 
            {
                SelectListItem item = new SelectListItem();
                item.Text = dc.DieaseName;
                item.Value = dc.DieaseCategoryId.ToString();
                items.Add(item);
            }
            Categories = items;
        }

        public List<Category> NewsCategories { get; set; }

        [DisplayName("Danh mục tin liên quan: ")]
        [Required(ErrorMessage = "Nếu bạn không chọn danh mục, website sẽ không thể tự động hiển thị tin tức cho bệnh án này")]
        public List<String> SelectedNewsCategories { get; set; }

        public void setSelectedNewsCategories(List<Category> categories)
        {
            SelectedNewsCategories = new List<String>();
            foreach (Category c in categories)
            {
                SelectedNewsCategories.Add(c.CategoryId.ToString());
            }
        }
     }


    public class ManageDiseaseBusiness 
    {

        public PaginateList<Disease> Search(string keyWord, string field, int pageIndex, int pageSize, string orderField, string direction) 
        {
        
            DrugStoreEntities entities = new DrugStoreEntities();
            IQueryable<Disease> diseases = entities.Diseases;
            diseases = from d in diseases
                       orderby d.DiesaseName ascending
                       select d;
            List<Disease> list = diseases.ToList();
            if (!String.IsNullOrEmpty(keyWord)) 
            {
                if ("Disease".Equals(field, StringComparison.OrdinalIgnoreCase)) 
                {
                    diseases = diseases.Where(d => d.DiesaseName.Contains(keyWord));
                }
            }
            PaginateList<Disease> results = new PaginateList<Disease>(diseases, pageIndex, pageSize, keyWord, field, orderField, direction);
            return results;
        }

        public void AddDisease(ManageDiseaseModels dis) 
        { 
            DrugStoreEntities entities = new DrugStoreEntities();

            Disease disease = new Disease();
            disease.DiseaseId = Guid.NewGuid();
            disease.DiesaseName = dis.DiseaseName;
            disease.BriefDesc = dis.BriefDesc;
            disease.Content = dis.Content;
            disease.Status = 1;            
            disease.ImgPath = dis.ImgPatch;

            Guid productId = new Guid();
            Guid.TryParse("9c0df878-46fa-470a-a753-858b3291ad03",out productId);
            Guid categoryId = new Guid();
            Guid.TryParse(dis.DiseaseCategoryId, out categoryId);
            disease.ProductId = productId;
            disease.DiseaseCategoryId = categoryId;

            foreach (String c in dis.SelectedNewsCategories)
            {
                Guid id;
                Guid.TryParse(c, out id);
                if (id != null)
                {
                    Category category = entities.Categories.FirstOrDefault(cat => cat.CategoryId == id);
                    if (category != null)
                    {
                        disease.Categories.Add(category);
                    }
                }
            }

            entities.Diseases.AddObject(disease);
            entities.SaveChanges();
           
        }

        public ManageDiseaseModels GetDiseaseById(String id)
        {
            Guid DiseaseId = Guid.Empty;
            try
            {
                DiseaseId = Guid.Parse(id);
            }
            catch (Exception ex) 
            {
                throw new ParameterInvalidException("","Không tồn tại bệnh án này!");
            }
            DrugStoreEntities entities = new DrugStoreEntities();
            Disease disease = entities.Diseases.FirstOrDefault(d=>d.DiseaseId == DiseaseId);

            if (disease == null) 
            {
                throw new ParameterInvalidException("", "Không tồn tại bệnh án này !");
            }

            ManageDiseaseModels model = new ManageDiseaseModels();
            
            model.DiseaseId = disease.DiseaseId.ToString();
            model.DiseaseCategoryId = disease.DiseaseCategoryId.ToString();
            model.DiseaseName = disease.DiesaseName;
            model.BriefDesc = disease.BriefDesc;
            model.ImgPatch = disease.ImgPath;
            model.Content = disease.Content;
            model.setSelectedNewsCategories(disease.Categories.ToList());
            return model;            
        }  
        public void UpdateDisease(ManageDiseaseModels model) 
        {
            DrugStoreEntities entities = new DrugStoreEntities();
            Guid diseaseId = Guid.Empty;
            if (!Guid.TryParse(model.DiseaseId, out diseaseId)) {
                throw new Exception("Bện án này không tồn tại");
            }
            Disease disease = entities.Diseases.FirstOrDefault(d=>d.DiseaseId == diseaseId);
            if (disease == null) 
            {
                throw new Exception("Bện án này không tồn tại");
            }
            disease.DiesaseName = model.DiseaseName;
            disease.BriefDesc = model.BriefDesc;
            disease.Content = model.Content;

            Guid categoryId = new Guid();
            if (!Guid.TryParse(model.DiseaseCategoryId, out categoryId)) {
                        throw new Exception("Bện án này không tồn tại");
            }
            disease.DiseaseCategoryId = categoryId;

            if (!String.IsNullOrEmpty(model.ImgPatch))
            {
                if (!String.IsNullOrEmpty(disease.ImgPath))
                {
                    FileInfo file = new FileInfo(HttpContext.Current.Server.MapPath(disease.ImgPath));
                    if (file.Exists)
                    {
                        file.Delete();
                    }
                }
                disease.ImgPath = model.ImgPatch;
            }
            disease.Categories.Clear();
            foreach (String c in model.SelectedNewsCategories)
            {
                Guid id;
                Guid.TryParse(c, out id);
                if (id != null)
                {
                    Category category = entities.Categories.FirstOrDefault(cat => cat.CategoryId == id);
                    if (category != null)
                    {
                        disease.Categories.Add(category);
                    }
                }
            }

            entities.SaveChanges();
        }

        public void Delete(String id) 
        {
            DrugStoreEntities entities = new DrugStoreEntities();
            Guid diseaseId = Guid.Empty;
            if (!Guid.TryParse(id, out diseaseId )) 
            {
                throw new Exception("Bệnh án này không tồn tại");
            }

            Disease disease = entities.Diseases.FirstOrDefault(d=>d.DiseaseId == diseaseId);
            if (disease == null) 
            {
                throw new Exception("Benh an nay khong ton tai !");
            }
            entities.DeleteObject(disease);
            entities.SaveChanges();
            if (!String.IsNullOrEmpty(disease.ImgPath)) 
            {
                FileInfo file = new FileInfo(HttpContext.Current.Server.MapPath(disease.ImgPath));
                if (file.Exists)
                {
                    file.Delete();
                }
            }
        }
        public List<DiseaseCategory> GetCategories() 
        {
            DrugStoreEntities entities = new DrugStoreEntities();
            return entities.DiseaseCategories.ToList();
        }   
    }
}